# -*- coding:utf-8 -*-

import os
import subprocess
import inspect
from utils.io_utils import convert_abspath
from utils.tb_utils import DefaultThread
import time
from utils.tb_utils import kill_tensorboard


log_dir = convert_abspath('data/log/cnn/lenet5')
command = 'tensorboard --logdir=' + log_dir


def open_tensorboard2():
    process = subprocess.Popen(
        command,
        shell=True, stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    # p.communicate()
    # process.stdin.write('^C\n'.encode('utf-8'))
    i = 0
    while True:
        if not process.poll():
            i += 1
            print('程序执行中...{}'.format(i))
            time.sleep(1)
            if i > 10:
                process.kill()
        else:
            print('程序执行完毕, 状态码为：%s' % process.poll())
            break


def run_cmd(print_output=True, universal_newlines=True):
    p = subprocess.Popen(
        command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        shell=True, universal_newlines=universal_newlines
    )
    if print_output:
        output_array = []
        while True:
            line = p.stdout.readline()
            if not line:
                break
            print(line.strip("/n"))
            output_array.append(line)
        output = "".join(output_array)
    else:
        output = p.stdout.read()
    p.wait()
    errout = p.stderr.read()
    if print_output and errout:
        print(print_output, errout)

    p.stdout.close()
    p.stderr.close()
    return output, p.returncode


def return_test():
    a = 1
    b = 2
    return a, b

if __name__ == '__main__':
    b = inspect.getsourcelines(run_cmd)[0][-1]
    a = inspect.signature(run_cmd)
    j = return_test()
    print(a)
